import * as mobx from 'mobx';
import * as API from '../../apis/standCustomReport';
import {message} from 'antd';
import {WeaLocaleProvider} from 'ecCom';
import has from 'lodash/has';
import remove from 'lodash/remove';
import {StandardCustomReportTableStore} from './reportTableStore';
import cloneDeep from 'lodash/cloneDeep';
import {Modal} from 'antd';
const {observable, action, computed} = mobx;
const getLabel = WeaLocaleProvider.getLabel;

export class StandardCustomReportStore {

    @observable loading = false;
    @observable loadData = true;
    @observable tableStore = new StandardCustomReportTableStore();
    @observable tabKey = 0;
    dataKey = '';
    topTab = [];


    @observable modalVisible = false; //存为模板
    baseParams = {};
    configs = {};

    @observable colSetVisible = false;   
    @observable colSetdatas = []; 
    @observable colSetKeys = [];

    @observable exportExcelUrl = '';
    noRight = false;
    title = '';
    doComponentDidUpdate = true;
    currentConfig = [];

    @observable exportInfo = [];

    //渲染组件
    @observable renderComponent = 0;

    @observable specialConditionValues = {};

    timer = null;



    constructor() {

        this.getReportCondition = this.getReportCondition.bind(this);
        this.clearDatas = this.clearDatas.bind(this);
        this.search = this.search.bind(this);
        this.saveTemplate = this.saveTemplate.bind(this);
        this.switchTab = this.switchTab.bind(this);
        this.deleteModule = this.deleteModule.bind(this);
        this.updateConfigItem = this.updateConfigItem.bind(this);
        this.exportExcel = this.exportExcel.bind(this);
        this.setLoading = this.setLoading.bind(this);
        this.loadConfig = this.loadConfig.bind(this);
        this.resetDoDidUpdate = this.resetDoDidUpdate.bind(this);
        this.clearAllStatus = this.clearAllStatus.bind(this);
        this.setSpecialConditionValues =this.setSpecialConditionValues.bind(this);
        this.cancelTask = this.cancelTask.bind(this);
        this.loadExportInfo = this.loadExportInfo.bind(this);
        this.setLoadData = this.setLoadData.bind(this);
    }


    @action('报表查询条件')
    getReportCondition(params = {}) {
        this.baseParams = params;
        this.loadConfig(params.tabKey);
    }

    switchTab(key) {
        this.doComponentDidUpdate = true;
        this.tabKey = key;
        this.baseParams = {...this.baseParams, tabKey : key,templateid: key};
        this.baseParams.tabKey = key;
        this.baseParams.templateid = key;
        this.loadConfig(key);
    }

    loadConfig(key = 0,isLoad = false){
        if (!has(this.configs, `key_${key}`) || isLoad) {
            this.currentConfig = [];
            this.setLoading(true);
            const {tabKey} = this.baseParams
            if (tabKey) {
                this.baseParams = {...this.baseParams, templateid: tabKey};
            }
            API.getReportCondition(this.baseParams).then((data = {}) => {
                const {configs = [],reportname = '', tabs = [],noRight = false} = data;
                this.noRight = noRight;
                if(!noRight) {
                    if(true) {
                        this.title = reportname;
                        this.topTab = tabs;
                    }
                    const updateConfig = {};
                    updateConfig[`key_${key}`] = cloneDeep(configs);
                    this.configs = Object.assign({},mobx.toJS(this.configs),updateConfig);
                    this.currentConfig = cloneDeep(configs);
                }
                this.setLoading(false);
            });
        } else {
            this.currentConfig = [];
            this.renderComponent  = new Date().getTime();
            let timer = setTimeout(()=>{
                let config = mobx.toJS(this.configs[`key_${this.tabKey}`]);
                this.currentConfig = cloneDeep(config);
                this.renderComponent  = new Date().getTime();
            },0);
        }
    }

    setLoading(bool = false) {
        if(this.loading != bool)  this.loading = bool;
    }

    setLoadData(bool = false) {
        if(this.loadData != bool)  this.loadData = bool;
    }

    setColSetVisible = (bool)=>{
        this.colSetVisible = bool;
    }
    
    @action
    getColSetData = (reportid,method) => {
        const  colSetParams = {};
        colSetParams['method'] = method;
        colSetParams['reportid'] = reportid;
        colSetParams['dataKey'] = '';
        colSetParams['modeid'] = this.tabKey ;
        API.tableColSet(colSetParams).then(data => {
            if (data.status) {
                 const keys = [];
                 data.destdatas.forEach(d => {
                     keys.push(d.dataIndex);
                 });
                 const datas = [].concat(data.destdatas).concat(data.srcdatas).filter((d) => {
                     return !!d.title && d.customCol != "false";
                 });
                 const newDatas = [];
                 datas.map(d => newDatas.push({id: d.dataIndex, name: d.title}));
                 this.colSetdatas = newDatas;
                 this.colSetKeys = keys;             
            } else {
                message.error('接口错误，请重新提交');
            }      
        })
    }
    setSystemIds =(datas)=>{
        //数据发生改变
        this.colSetKeys = datas;
    }

    @action
    saveColumnsSet =( reportid, method )=>{
        const  saveColumnsSetParams = {};
        saveColumnsSetParams['method'] = method;
        saveColumnsSetParams['reportid'] = reportid;
        saveColumnsSetParams['dataKey'] = '';
        saveColumnsSetParams['modeid'] = this.tabKey ;
        saveColumnsSetParams['systemIds'] = mobx.toJS(this.colSetKeys).join(',') ;
        API.tableColSet(saveColumnsSetParams).then(data => {
            this.colSetVisible = false;
        });
    }

    @action
    saveColumnsReset =(reportid, method,redefault)=>{
        const  resetParams = {};
        resetParams['method'] = method;
        resetParams['reportid'] = reportid;
        resetParams['dataKey'] = '';
        resetParams['modeid'] = this.tabKey ;
        resetParams['redefault'] = redefault;
        API.tableColSet(resetParams).then(data => {
            this.colSetVisible = false;
        });
    }


    @action
    clearDatas(isCondition = false) {
        if (isCondition) {
            this.baseParams = {};
        } else {
            this.tableStore = new StandardCustomReportTableStore();
            this.exportExcelUrl = "";
        }
    }

    @action('初始化所有状态')
    clearAllStatus(){
        this.tableStore = new StandardCustomReportTableStore();
        this.exportExcelUrl = '';
        this.tabKey = 0;
        this.dataKey = '';
        this.topTab = [];
        this.modalVisible = false;
        this.baseParams = {};
        this.configs = {};
        this.noRight = false;
        this.title = '';
        this.doComponentDidUpdate = true;
        this.currentConfig = [];
        this.renderComponent = 0;
    }

    @action('查询报表数据')
    search(params = {}) {
        this.setLoading(true);
        API.getReportData(params).then((data = {}) => {
            const {noRight = false, sessionkey = '', reportname = '', sortFields = [],sumMainFields = [],sumfielddecimals = {}} = data;
                this.noRight = noRight;
            if(!noRight){
                this.tableStore.getDatas(sessionkey);
                this.tableStore.setReportFields(sortFields,sumMainFields,sumfielddecimals);
                this.dataKey = sessionkey;
                this.title = reportname;
            }
            this.setLoading(false);
            this.exportInfoParams = {reportid:params.reportid};
            this.loadExportInfoInterval();
        });
    }

    @action("保存模板")
    saveTemplate(updateParams = {}) {
        this.setLoading(true);
        const params = { ...this.baseParams, ...updateParams};
        API.saveReportTemplate(params).then((data = {}) => {
            const {success, templateid} = data;
            if (success && templateid > 0) {
                const {moduleName = ''} = updateParams;
                this.topTab.push({'key': templateid, 'title': moduleName});
                this.switchTab(templateid);
            } else {
                delete this.configs[`key_${this.tabKey}`];
                this.currentConfig = [];
                this.baseParams = {...this.baseParams, templateid: this.tabKey};
                setTimeout(()=>{
                    this.loadConfig(this.tabKey);
                },0);
                this.setLoading(false);
            }
        })
    }
    

    @action("删除模板")
    deleteModule() {
        this.setLoading(true);
        API.delReportTemplate({templateid: this.tabKey}).then((data) => {
            const {success} = data;
            if (success) {
                message.success(getLabel(20461, '删除成功'));
                let tabs = this.topTab;
                remove(tabs, (item) => {
                    return item.key == this.tabKey;
                })
                delete this.configs[`key_${this.tabKey}`];
                this.topTab = tabs;
                this.switchTab(0);
            } else {
                message.error(getLabel(20462, '删除失败'));
            }
            this.setLoading(false);
        })
    }

    @action("更新config")
    updateConfigItem(index, configItemIndex, updateObj) {
        if (this.currentConfig) {
            const configitem = this.currentConfig[index];
            configitem.config[configItemIndex] = updateObj;
            this.renderComponent  = new Date().getTime();
        }
    }

    exportExcel(bool = false,reportid) {
        const {sortFields = [],sumMainFields = []} = this.tableStore;
        const tempThis = this;
        let params = {tableKey:this.dataKey,sortFields:sortFields.join(','),sumMainFields:sumMainFields.join(','),reportid:reportid,filename:this.title};
        API.exportExcel(params).then((res) => {
            const code = res.code;
            const data = res.data;
            if(code == 0 ) {
                Modal.warning({
                    title: getLabel(131329, '信息确认'),
                    content: data,
                    okText: getLabel(83446, '确定'),
                    onOk() {
                        setTimeout(tempThis.loadExportInfoInterval, 2000);
                    },
                })
            }
            setTimeout(this.loadExportInfoInterval,2000);
        });
    }

    downloadExcel = (url = '',keyid = '') => {
        if(url) this.exportExcelUrl = url;
        let params = {...this.exportInfoParams,'method':'update',id:keyid,status:url ? '2':'3'};
        API.exportTask(params).then((res)=>{
            const {datas = []} = res;
            this.loadExportInfoInterval();
        })
    }

    cancelTask = (keyid = '')=>{
        let params = {id:keyid , 'method':'cancel'};
        API.cancelTask(params).then((res)=>{
            this.loadExportInfoInterval();
        })

    }

    loadExportInfo = () => {
        if(this.loadData) {
            this.setLoadData(false);
            API.exportTask({...this.exportInfoParams, 'method': 'list'}).then((res = {}) => {
                const {datas = []} = res;
                this.exportInfo = datas;

                let tmpdatas = datas.filter((item = {}) => item.status == 0);
                if (tmpdatas.length <= 0 && this.timer) {
                    clearInterval(this.timer);
                    this.timer = null;
                }
                this.setLoadData(true);
            })
        }
    }

    loadExportInfoInterval = () => {
        if(this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
        this.loadExportInfo();
        this.timer = setInterval(this.loadExportInfo,2000);
    }

    resetDoDidUpdate(){
        this.doComponentDidUpdate =false;
    }

    setSpecialConditionValues(value = {}){
        this.specialConditionValues = {...this.specialConditionValues,...value};
    }

    setTabKey=(tabKey)=>{
        this.tabKey = tabKey;
    }
}